package com.ruiyi.adrobot.component;

import com.alibaba.fastjson.JSONObject;
import com.ruiyi.adrobot.beans.*;
import com.ruiyi.adrobot.beans.dto.SimCodeSocketRequest;
import com.ruiyi.adrobot.beans.dto.TaskExcuteBaseInfo;
import com.ruiyi.adrobot.beans.socket.SocketRequest;
import com.ruiyi.adrobot.mongo.device.DeviceRepository;
import com.ruiyi.adrobot.mongo.robot.RobotRepository;
import com.ruiyi.adrobot.mongo.taskdetail.TaskDetailRepository;
import com.ruiyi.adrobot.service.accountinfo.AccountInfoService;
import com.ruiyi.adrobot.service.device.DeviceService;
import com.ruiyi.adrobot.service.vpn.VpnService;
import com.ruiyi.adrobot.utils.DateUtil;
import com.ruiyi.adrobot.utils.LoggerUtil;
import com.ruiyi.adrobot.web.socket.ChannelInitializerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by 51102 on 2017/6/24.
 */
@Component
public class TaskExcuter {
    @Autowired
    private TaskDetailRepository taskDetailRepository;
    @Autowired
    private RobotRepository robotRepository;
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private VpnService vpnService;
    @Autowired
    private AccountInfoService accountInfoService;
    public static Map<String, Queue> queueMap = new ConcurrentHashMap(); // 任务队列map
    public static List<String> stopTaskList = Collections.synchronizedList(new ArrayList<String>());
    public static Queue<SimCodeSocketRequest> checkSendStatusQueue = new ConcurrentLinkedQueue(); // 检查任务发送状态队列

    /**
     * 初始化netty
     */
    @Async
    public void initNetty() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializerHandler());
            //设置参数，TCP参数
            bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置，链接缓冲池的大小
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃，清除死链接
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送
            bootstrap.bind(2406).sync().channel().closeFuture().sync();
            LoggerUtil.debug("*************************Netty已启动************************");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Async
    public void offerTask2Queue(TaskDetail taskDetail) {
        List<TaskDetail.Task> tasks = taskDetailRepository.findTasksByTaskDetailIdAndNotSent(taskDetail.getId());
        int time = 1;
        for (TaskDetail.Task task : tasks) {
            try {
                LoggerUtil.info("步骤0");
                if (stopTaskList.contains(taskDetail.getId())) {
                    stopTaskList.remove(taskDetail.getId());
                    return;
                }
                LoggerUtil.info("步骤1");
                while (DateUtil.getTimeByString(task.getStartTime()) > new Date().getTime()) {
                    LoggerUtil.info("未到任务执行时间暂停60秒" + taskDetail.getId());
                    SECONDS.sleep(60);
                }
                LoggerUtil.info("步骤2");
                // 将任务放入queue
                String startDate = null;
                String endDate = null;
                Fun.Flow.Action action = null;
                for (TaskConfig.Flow flow : taskDetail.getFlows()) {
                    if (flow.getId().equals(task.getFlowId())) {
                        startDate = flow.getStartDate();
                        endDate = flow.getEndDate();
                        action = flow.getAction();
                        break;
                    }
                }
                LoggerUtil.info("步骤3");
                QueueTask queueTask = new QueueTask(taskDetail.getId(), taskDetail.getFun(), taskDetail.getGroupNames(), task, startDate, endDate, action, taskDetail.getDidType(), taskDetail.getDeviceType());
                LoggerUtil.info("步骤4");
                if (null == queueMap.get(taskDetail.getId())) {
                    Queue queue = new ConcurrentLinkedQueue();
                    queue.offer(queueTask);
                    queueMap.put(taskDetail.getId(), queue);
                } else {
                    queueMap.get(taskDetail.getId()).offer(queueTask);
                }
                LoggerUtil.info("步骤5");
                LoggerUtil.info(taskDetail.getId() + "队列池中任务数量" + queueMap.get(taskDetail.getId()).size());
                LoggerUtil.info(taskDetail.getId() + "任务已分配" + time++);
            } catch (Exception e) {
                LoggerUtil.error("任务分配线程发生异常:" + taskDetail.getId());
                LoggerUtil.info(taskDetail.getId() + "队列池中任务数量" + queueMap.get(taskDetail.getId()).size());
                e.printStackTrace();
                continue;
            }
        }
        LoggerUtil.info("发现任务且已分配完成暂停30秒" + taskDetail.getId());
        try {
            SECONDS.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void excuteQueueTask() {
        while (true) {
            try {
                if (queueMap.size() > 0) {
                    for (Map.Entry<String, Queue> entry : queueMap.entrySet()) {
                        QueueTask queueTask = (QueueTask) entry.getValue().poll();
                        if (null == queueTask) {
                            queueMap.remove(entry.getKey());
                            break;
                        }

                        if (!excuteTask(queueTask)) {
                            queueMap.get(queueTask.getTaskDetailId()).offer(queueTask);
                        }
                        LoggerUtil.info(queueTask.getTaskDetailId() + "队列中任务数量:" + queueMap.get(queueTask.getTaskDetailId()).size());
                    }
                } else {
                    LoggerUtil.info("线程队列中没有任务暂停10秒");
                    SECONDS.sleep(10);
                }
            } catch (Exception e) {
                LoggerUtil.info("任务停止后发生读取异常，任然可正常运行");
            }
        }
    }


    private Boolean excuteTask(QueueTask queueTask) throws InterruptedException {
        // 开始分配任务
        long startTime = System.currentTimeMillis();
        TaskExcuteBaseInfo taskExcuteBaseInfo = buildTaskExcuteBaseInfo(queueTask);
        if (taskExcuteBaseInfo.getErrorCode() != 0) {
            TimeUnit.SECONDS.sleep(1);
            return false;
        }
        String excuteSimCode = taskExcuteBaseInfo.getExcuteSimCode();
        Device excuteDevice = taskExcuteBaseInfo.getExcuteDevice();
        // 任务执行的模拟设备信息
        queueTask.getTask().setDevice(excuteDevice);
        // 发送任务
        SocketRequest<Map<String, Object>> socketRequest = buildSocketRequest(queueTask.getTaskDetailId(), queueTask.getTask(), queueTask.getAction());
        NettyChannelhandlerContextMap.get(excuteSimCode).writeAndFlush(socketRequest.toString());
        // 放入队列检查是否发送成功，不成功重发一次
        checkSendStatusQueue.offer(new SimCodeSocketRequest(excuteSimCode, socketRequest));
        // 记录任务相关信息
        updateTaskInfo(queueTask.getTaskDetailId(), queueTask.getTask(), excuteSimCode, excuteDevice, taskExcuteBaseInfo.getTaskDynamicInfos(), queueTask.getFun());
        LoggerUtil.info("任务已发送用时:" + (System.currentTimeMillis() - startTime));
        return true;
    }

    private TaskExcuteBaseInfo buildTaskExcuteBaseInfo(QueueTask queueTask) {
        TaskExcuteBaseInfo taskExcuteBaseInfo = new TaskExcuteBaseInfo();
        try {
            boolean virtual = queueTask.getDeviceType() == 1 ? true : false;
            // 筛选出組中能执行任务、处于空闲、在线的Robot
            List<Robot> canExcuteRobots = robotRepository.getCanExcuteRobotsByOnlineAndBusyAndGroupNameAndLockTimeLessThan(queueTask.getGroupNames());
            List<String> usedImeis = taskDetailRepository.findUsedImeisById(queueTask.getTaskDetailId());
            if (canExcuteRobots.size() == 0) {
                LoggerUtil.info("沒有可用的Robot:暂停1秒");
                return TaskExcuteBaseInfo.errorCode(1);
            }
            if (queueTask.getTask().getStepType3() != -1) {
                // 根据空闲设备的设备型号循环查找匹配的账号
                AccountInfo.Account account = accountInfoService.findRandomAccount(queueTask.getFun(), virtual, queueTask.getStartDate(), queueTask.getEndDate(), usedImeis, canExcuteRobots);
                if (null == account) {
                    LoggerUtil.info("老用户不足");
                    return TaskExcuteBaseInfo.errorCode(2);
                }
                taskExcuteBaseInfo.setExcuteSimCode(account.getExcuteSimCode());
                taskExcuteBaseInfo.setExcuteDevice(deviceService.findDeviceByImei(account.getImei(), virtual));
                // 输入用户名和密码赋值
                taskExcuteBaseInfo.setTaskDynamicInfos(fillAccount(queueTask, account));
            } else {
                Device excuteDevice = deviceService.findRandomNotUsedDevice(queueTask.getFun(), virtual, canExcuteRobots);
                if (null == excuteDevice) {
                    LoggerUtil.info("设备型号不足");
                    return TaskExcuteBaseInfo.errorCode(3);
                }
                taskExcuteBaseInfo.setExcuteSimCode(excuteDevice.getExcuteSimCode());
                taskExcuteBaseInfo.setExcuteDevice(excuteDevice);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.info("获取任务基本信息时，未知异常");
            return TaskExcuteBaseInfo.errorCode(5);
        }
        return taskExcuteBaseInfo;
    }

    private List<TaskDetail.Task.TaskDynamicInfo> fillAccount(QueueTask queueTask, AccountInfo.Account account) {
        List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos = new LinkedList<>();
        queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3()).setViewText(account.getUserName());
        taskDynamicInfos.add(new TaskDetail.Task.TaskDynamicInfo(queueTask.getTask().getStepType3(), account.getUserName()));
        Integer stepType;
        int l = 1;
        do {
            stepType = queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3() + l).getStepType();
            l++;
        } while (stepType != 4);
        queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3() + l - 1).setViewText(account.getPwd());
        taskDynamicInfos.add(new TaskDetail.Task.TaskDynamicInfo(queueTask.getTask().getStepType3() + l - 1, account.getPwd()));
        return taskDynamicInfos;
    }


    private void updateTaskInfo(String taskDetailId, TaskDetail.Task task, String excuteSimCode, Device excuteDevice, List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos, Integer fun) {
        // 记录二次登陆使用的imei
        updateUsedImei(taskDetailId, excuteDevice.getImei());
        // 标记该设备已使用
        signUsedDevice(excuteDevice, fun);
        // 锁定Robot60秒
        lockRobot(excuteSimCode);
        // 记录任务详细信息
        updateTask(taskDetailId, task, excuteSimCode, taskDynamicInfos);
    }

    private void signUsedDevice(Device excuteDevice, Integer fun) {
        Device device = deviceService.findOne(excuteDevice.getImei());
        if (null == device) {
            VirtualDevice virtualDevice = deviceService.findVirtualDeviceByImei(excuteDevice.getImei());
            if (!virtualDevice.getUsedFuns().contains(fun)) {
                virtualDevice.getUsedFuns().add(fun);
                deviceService.saveOrUpdateVirtualDeviceAccounts(virtualDevice);
            }
        } else {
            if (!device.getUsedFuns().contains(fun)) {
                device.getUsedFuns().add(fun);
                deviceService.saveOrUpdate(device);
            }
        }
    }

    private void updateUsedImei(String taskDetailId, String imei) {
        Update update = new Update();
        update.push("usedImeis", imei);
        taskDetailRepository.updateById(taskDetailId, update);
    }

    private void lockRobot(String excuteSimCode) {
        Update updateRobot = new Update();
        updateRobot.set("lockTime", new Date().getTime() + 1000 * 30);
        robotRepository.updateBySimCode(excuteSimCode, updateRobot);
    }

    private void updateTask(String taskDetailId, TaskDetail.Task task, String excuteSimCode, List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos) {
        Update update = new Update();
        update.set("tasks.$.sent", true);
        update.set("tasks.$.excuteSimCode", excuteSimCode);
        update.set("tasks.$.taskDynamicInfos", taskDynamicInfos);
        taskDetailRepository.updateTaskByNum(taskDetailId, task.getNum(), update);
    }

    private SocketRequest<Map<String, Object>> buildSocketRequest(String taskDetailId, TaskDetail.Task task, Fun.Flow.Action action) {
        Map<String, Object> socketMap = new LinkedMap();
        socketMap.put("taskDetailId", taskDetailId);
        socketMap.put("num", task.getNum());
        socketMap.put("imei", task.getDevice().getImei());
        socketMap.put("action", action);
        socketMap.put("device", task.getDevice());
        return (SocketRequest<Map<String, Object>>) new SocketRequest("start_fun", socketMap);
    }

    @Async
    public void checkSendStatus() {
        while (true) {
            try {
                if (checkSendStatusQueue.size() > 0) {
                    SimCodeSocketRequest simCodeSocketRequest = checkSendStatusQueue.poll();
                    Boolean busy = robotRepository.findBySimCode(simCodeSocketRequest.getSimCode()).getBusy();
                    if (!busy) {
                        LoggerUtil.info("发送失败,暂停5秒后重新检查：" + simCodeSocketRequest.getSimCode());
                        try {
                            TimeUnit.SECONDS.sleep(5);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        busy = robotRepository.findBySimCode(simCodeSocketRequest.getSimCode()).getBusy();
                        if (!busy) {
                            ChannelHandlerContext ctx = NettyChannelhandlerContextMap.get(simCodeSocketRequest.getSimCode());
                            if (null != ctx) {
                                ctx.writeAndFlush(simCodeSocketRequest.getSocketRequest().toString());
                                LoggerUtil.info(simCodeSocketRequest.getSimCode() + "任务已重发");
                                continue;
                            } else {
                                LoggerUtil.info(simCodeSocketRequest.getSimCode() + "已不在线,发送失败");
                                continue;
                            }
                        }
                    }
                    LoggerUtil.info("成功发送给：" + simCodeSocketRequest.getSimCode());
                } else {
                    try {
                        LoggerUtil.info("没有可检查的任务暂停10秒");
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                LoggerUtil.info("检查任务发送情况线程发生异常");
            }

        }
    }

}
